from PIL import Image, ImageDraw, ImageFont, ImageFilter
import random
from django.utils.six import BytesIO


class Code(object):
    def __init__(self, basic, count):
        self.basic = basic
        self.width = basic * count
        self.height = basic

    def getChar(self):
        return chr(random.randint(65, 90))

    def getColor(self):
        return (random.randint(64, 255), random.randint(64, 255), random.randint(64, 255))

    def getColor2(self):
        return (random.randint(32, 127), random.randint(32, 127), random.randint(32, 127))

    def generatorImage(self):
        #  生成图片
        image = Image.new('RGB', (self.width, self.height), (255, 255, 255))
        # 创建Font对象:
        font = ImageFont.truetype('/Library/Fonts/GillSans.ttc', 36)
        # 创建Draw对象:
        draw = ImageDraw.Draw(image)
        # 填充每个像素:
        for x in range(self.width):
            for y in range(self.height):
                draw.point((x, y), fill=self.getColor())
        # 输出文字:
        listChar = []
        for t in range(6):
            char = self.getChar()
            listChar.append(char)
            draw.text((self.basic * t + 10, 10), char,
                      font=font, fill=self.getColor2())
            #image = image.filter(ImageFilter.BLUR)
        # return 'hola'
        buffer = BytesIO()
        image.save(buffer, 'png')
        image_stream = buffer.getvalue()
        return [''.join(listChar), image_stream]
